<?php

namespace app\admin\controller;

use think\Db;
use think\Request;
use think\Validate;
use app\facade\Redis;
use app\models\{User as Users, Locklist, Relesstaitc, Incomelist, Jsrlist, JsrlistLog, Listcoin, Money, Moneylog};
use think\Facade\Config as Configs;


class Lock extends Base
{
    public function Index()
    {
        $ModelFun = new Locklist();
        $data = $this->request->get();
        $list = $ModelFun->order('id desc');
        if (!empty($data['mobile'])) {
            $id = (new Users())->where('id|mobile', $data['mobile'])->value('id');
            $list = $list->where('user_id', $id);
        }
        if (!empty($data['status'])) {
            $list = $list->where('status', $data['status']);
        }
        $rele = (new Relesstaitc())->order('dates desc')->where('dates', '<', date('Y-m-d'))->find();
        $todaytotal = $ModelFun->where('created', '>=', date('Y-m-d'))->sum('number');
        $todayrele = (new Moneylog())->where('created', '>=', date('Y-m-d'))->where(['type' => [4, 5]])->sum('money');
        $list = $list->paginate(15, false, ['query' => $this->request->param()])->each(function ($user) {
            if ($user['user_id'] > 0) {
                $user['mobile'] = (new Users())->where('id', $user['user_id'])->value('mobile');
            } else {
                $user['mobile'] = '';
            }
            return $user;
        });
        return view('', ['list' => $list, 'rele' => $rele, 'todaytotal' => $todaytotal, 'todayrele' => $todayrele]);
    }


    public function lockstr()
    {
        if ($this->request->isPost()) {
            $rdslist = Redis::get('clickreturn');
            if ($rdslist) {
                return json(['code' => 1, 'data' => [], 'msg' => '请' . $rdslist . 's后再试']);
            }
            Redis::setex('clickreturn', 2, 1);
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require|gt:0',
            ], [
                'id.require' => 'ID不能为空',
                'id.require' => 'ID必须大于0',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $lists = (new Locklist())->where('id', $data['id'])->find();
            if (empty($lists) || $lists['status'] != 1) {
                return json(['status' => 1, 'msg' => '订单状态不可修改']);
            }
            $user = (new Money())->where(['user_id' => $lists['user_id'], 'type' => 1])->find();
            $userlock = (new Users())->where('id', $lists['user_id'])->value('lockmoney');
            $userlock = empty($userlock) ? 0 : $userlock;
            Db::startTrans();
            try {
                if ($userlock < $lists['money']) {
                    (new Users())->where(['id' => $lists['user_id'], 'lockmoney' => $userlock])->update(['lockmoney' => 0]);
                } else {
                    (new Users())->where(['id' => $lists['user_id'], 'lockmoney' => $userlock])->setDec('lockmoney', $lists['money']);
                }
                $user = (new Money())->where(['user_id' => $lists['user_id'], 'type' => 1])->find();
                (new Money())->where(['user_id' => $lists['user_id'], 'type' => 1])->setInc('money', $lists['number']);
                (new Moneylog())->insert([
                    'user_id' => $user['user_id'],
                    'befores' => $user['money'],
                    'money' => $lists['number'],
                    'after' => ($user['money'] + $lists['number']),
                    'cointype' => 1,
                    'type' => 6,
                    'dates' => date('Y-m-d'),
                    'info' => '系统解仓操作',
                    'source' => $lists['id']
                ]);
                (new Locklist())->where(['id' => $lists['id'], 'status' => 1])->update(['status' => 2]);
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return json(['status' => 1, 'msg' => '解仓失败，请重试']);
            }
            return json(['status' => 0, 'msg' => '解仓成功']);
        }
    }

    public function handfee()
    {
        $ModelFun = new Incomelist();
        $data = $this->request->get();
        $list = $ModelFun->order('id desc');
        if (!empty($data['status'])) {
            $list = $list->where('status', $data['status']);
        }
        $list = $list->paginate(15, false, ['query' => $this->request->param()]);
        return view('', ['list' => $list]);
    }

    public function jsr()
    {
        $ModelFun = new Jsrlist();
        $data = $this->request->get();
        $list = $ModelFun->order('id desc');
        $list = $list->paginate(15, false, ['query' => $this->request->param()]);
        return view('', ['list' => $list]);
    }

    public function jsr_add()
    {
        if ($this->request->isPost()) {
            $rdslist = Redis::get('clickreturn');
            if ($rdslist) {
                return json(['code' => 1, 'data' => [], 'msg' => '请' . $rdslist . 's后再试']);
            }
            Redis::setex('clickreturn', 2, 1);
            $data = $this->request->post();
            $validate = new Validate([
                'jsrnum' => 'require',
                'dates' => 'require',
                'synum' => 'require',
                'prices' => 'require',
            ], [
                'jsrnum.require' => '发放总量不能为空',
                'dates.require' => '发放时间不能为空',
                'synum.require' => '发放剩余数量不能为空',
                'prices.require' => '发放单价不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            if (empty($data['id'])) {
                $result = (new Jsrlist())->insertGetId($data);
                $data['id'] = $result;
            } else {
                $result = (new Jsrlist())->allowField(true)->save($data, ['id' => $data['id']]);
            }
            $jsrredis = 'Jsrlist' . $data['id'];
            if ($result) {
                Redis::set($jsrredis, $data['synum']);
                return json(['status' => 0, 'msg' => '操作成功']);
            } else {
                return json(['status' => 1, 'msg' => '操作失败']);
            }
        } else {
            $id = $this->request->get('id');
            $row = (new Jsrlist())->where('id', $id)->find();
            return view('', ['row' => $row]);
        }
    }

    public function jsrlog()
    {
        $ModelFun = new JsrlistLog();
        $data = $this->request->get();
        $list = $ModelFun->order('id desc');
        if (!empty($data['mobile'])) {
            $id = (new Users())->where('id|mobile', $data['mobile'])->value('id');
            $list = $list->where('user_id', $id);
        }
        if (!empty($data['pmobile'])) {
            $pid = (new Users())->where('id|mobile', $data['pmobile'])->value('id');
            $list = $list->where('comeuser_id', $pid);
        }
        if (!empty($data['type'])) {
            $list = $list->where('type', $data['type']);
        }
        $list = $list->paginate(15, false, ['query' => $this->request->param()])->each(function ($user) {
            $user['mobile'] = (new Users())->where('id', $user['user_id'])->value('mobile');
            if ($user['comeuser_id'] > 0) {
                $user['pmobile'] = (new Users())->where('id', $user['comeuser_id'])->value('mobile');
            } else {
                $user['pmobile'] = '';
            }
            return $user;
        });
        return view('', ['list' => $list]);
    }


    public function Listcoin()
    {
        $ModelFun = new Listcoin();
        $data = $this->request->get();
        $list = $ModelFun->order('user_id desc');
        if (!empty($data['mobile'])) {
            $id = (new Users())->where('id|mobile', $data['mobile'])->value('id');
            $list = $list->where('user_id', $id);
        }
        $list = $list->paginate(15, false, ['query' => $this->request->param()])->each(function ($user) {
            $user['mobile'] = (new Users())->where('id', $user['user_id'])->value('mobile');
            return $user;
        });
        return view('', ['list' => $list]);
    }

    public function listcoinstr()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'id' => 'require',
            'type' => 'require',
        ], [
            'id.require' => 'ID不能为空',
            'type.require' => '审核类型不能为空',
        ]);
        if (!$validate->check($data)) {
            return json(['status' => 1, 'data' => [], 'msg' => $validate->getError()]);
        }
        $Listcoin = (new Listcoin())->where('id', $data['id'])->find();
        if (empty($Listcoin) || $Listcoin['status'] != 1) {
            return json(['status' => 1, 'data' => [], 'msg' => '订单状态不可修改']);
        }
        Db::startTrans();
        try {
            (new Listcoin())->where('id', $data['id'])->update(['status' => $data['type']]);
            if ($data['type'] == 3 && $Listcoin['coinnum'] > 0) {
                $usermoney = (new Money())->where(['user_id' => $Listcoin['user_id'], 'type' => 1])->find();
                (new Money())->where(['user_id' => $Listcoin['user_id'], 'type' => 1, 'money' => $usermoney['money']])
                    ->inc('money', $Listcoin['coinnum'])
                    ->update();
                (new Moneylog())->insert([
                    'user_id' => $Listcoin['user_id'],
                    'befores' => $usermoney['money'],
                    'money' => $Listcoin['coinnum'],
                    'after' => ($usermoney['money'] + $Listcoin['coinnum']),
                    'cointype' => 1,
                    'type' => 17,
                    'info' => '申请上币驳回返回' . $Listcoin['coinnum'] . '个'
                ]);
            }
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->result([], 1, '审核失败，请稍后重试');
        }
        return json(['status' => 0, 'data' => [], 'msg' => '审核成功']);
    }
}
